package org.eclipse.football;

import java.io.IOException;


import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.football.web.*;

public class TeamServlet extends HttpServlet implements Servlet {
	// Override doPost function
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Read in information submitted by form
		String button = request.getParameter("Team Button");
		String name = request.getParameter("name");
		
		// Obtain existing league
		League league = (League) request.getSession(true).getAttribute("league");
		String username = (String) request.getSession(true).getAttribute("username"); //Aaron 11/9
		
		// Declare a team variable
		Team team;
		
		if(button.equals("Add Team")){
			// Make sure new team name is not null or blank
			if(name != null && !name.equalsIgnoreCase("")  && username != null && !username.equalsIgnoreCase("")){	//Aaron 11/9		
				// If so create a team with the given name
				team = new Team(name, username); //Aaron 11/9
		
				// Add the new team to this league
				league.addTeam(team);
			}
		
		}
		else if (button.equals("Delete Team")){
			team = (Team) request.getSession(true).getAttribute("team");
			league.deleteTeam(team);
		}
		
		// Write out the state of the league to a file
		league.writeState("league.txt");
				
		// Set league in the session
		request.getSession().setAttribute("league", league);
				
		// Set team back to null and set it in the session
		team = null;
		request.getSession().setAttribute("team", team);

		// Set all 3 player types to null in the session
		request.getSession().setAttribute("off", null);
		request.getSession().setAttribute("def", null);
		request.getSession().setAttribute("kicker", null);
				
				
		// Forward control back to stats.jsp
		getServletContext().getRequestDispatcher("/LeagueSummary.jsp").forward(request, response);
		
		
		// TODO Auto-generated method stub
		//super.doPost(request, response);
	}

}

